package fortunata.jspwikiplugins.vpoet;

import com.ecyrd.jspwiki.plugin.WikiPlugin;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.WikiContext;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.apache.log4j.Logger;

import java.util.Map;

import fortunata.FortunataPlugin;
import fortunata.fswapps.vpoet.Vpoet;

/**
 * This plugin is invoked automaticaly. If the httpRequest has a "visualizeItem", this will generate a FormSet with
 * values that will initialize the form elements. Otherwise, it will generate an empty FormSet
 */
public class SetFormVisualizeItem extends FortunataPlugin implements WikiPlugin {
    private static Logger log = Logger.getLogger( SetFormVisualizeItem.class );
    private OntModel m;
    private Vpoet vpoet;

    public String execute (WikiContext context, Map parameterMap) throws PluginException {
        vpoet = new Vpoet();
        StringBuffer sb = new StringBuffer();
        String uniqueID = context.getHttpRequest().getParameter(Vpoet.HttpRequestParameter_VisualizeElement);
        if (uniqueID != null){
           Individual indiv = getIndividual(context, uniqueID);
           sb.append("[{FormSet form='"+ Vpoet.VisualizeWikiPageName +"' " +
            "designID='" + indiv.getPropertyValue(m.getProperty(vpoet.getURI() + Vpoet.propNameDesignID)).toString() +  "' " +
            "providerID='" + indiv.getPropertyValue(m.getProperty(vpoet.getURI() + Vpoet.propNameProviderID)).toString() +  "' " +
            "}] \n");
        }else {
           sb.append("[{FormSet form='"+ Vpoet.VisualizeWikiPageName +"'}] \n");
        }
        //System.out.println(sb.toString());
        return renderWikiText(context, sb.toString());

    }
    private Individual getIndividual(WikiContext context, String elem)  throws PluginException{
        //Ensure definitions file exists
        vpoet.createDataModelFileIfNeeded(context);
        //Ensure individuals file exists
        vpoet.createIndividualsFileIfNeeded(context);

        //Creates an empty model
        m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF, null);
        //Reads Ontology
        vpoet.readSWAppModel(m, context);

        Individual indiv = m.getIndividual(vpoet.getURI() + elem);
        return indiv;
    }

}
